package com.sto.stoapp.activity.aviation.jipaoqi;

import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.LinkedList;

public class MeasureArrivePieceBehindActivity extends StoListenerActivity {
	private static byte[] backCommand = { 0x40, 0x02, 0x4F, 0x02, 0x52, 0x2A };

	public static final String LAST_COMMAND = "64, 2, 79, 5, 82, 42";

	private static final int CLEAR_QUEUE = 0x41;

	private BearingBlueThread bearingBlueThread;
	private OutputStream os;
	private InputStream is;

	public static final int BLUETOOTH_DATA_WHTA = 0x14;
	private boolean isFinish = false;
	private int[] companyMachCode = null;
	private String machineCode;
	private final int COURIER_RESULT = 0xfe;
	private String prevStationCode = "", prevStationName = "";
	private DataBusinessEntity dataBusiness;
	StoHhmEditText code, nextStationET;
	TextView lenghtTV, wideTV, volumeTV, highTV, weightTV;
	String decimalPlaces;
	JipaoqiDataEntity mData;
	LinkedList<JipaoqiDataEntity> queue;
	private boolean hasContent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weight_arrive_piece_scan);
		this.setTitleBottom("测量到件(后置)", HomeBroadAction.AVIATION_SCANNER_BROAD);
		initView();
		initListen();
		initPointLayout(true);
		initScanRecordAdapter(
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE, true);

		initScanListener();
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		decimalPlaces = StoFilePreference.getInstance(this)
				.getSelectedDecimalPlacesControl();
	}

	private void initView() {
		code = (StoHhmEditText) findViewById(R.id.sanning_code);
		nextStationET = (StoHhmEditText) findViewById(R.id.next_station);
		lenghtTV = (TextView) findViewById(R.id.lenght);
		wideTV = (TextView) findViewById(R.id.wide);

		volumeTV = (TextView) findViewById(R.id.volume);
		highTV = (TextView) findViewById(R.id.height);
		weightTV = (TextView) findViewById(R.id.weight);
		queue = new LinkedList<JipaoqiDataEntity>();
	}

	private void initListen() {
		// 上一站
		nextStationET.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
			}

			@Override
			public void onEditClickListener(View v) {
				selectPrevStation();
			}
		});
		nextStationET.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				prevStationCode = "";
				prevStationName = "";

			}
		});
		// 单号
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				nextStationET.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				onScanResults(code.getText().toString());
			}
		});
	}

	Handler jHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case BearingBlueThread.BLUETOOTH_NO_SETUP: // 蓝牙未设置
				bearingBlueThread.cancelDialog();
				weightTV.setText("蓝牙未设置");
				break;
			case BearingBlueThread.CONNECT_START: // 开始连接
				Helper.showToast(MeasureArrivePieceBehindActivity.this,
						"开始连接蓝牙");
				bearingBlueThread.showDialogByMessage("正在连接蓝牙");
				break;
			case BearingBlueThread.BLUETOOTH_CONNECTION_ERROR: // 蓝牙连接失败
				bearingBlueThread.cancelDialog();
				Helper.showToast(MeasureArrivePieceBehindActivity.this,
						"蓝牙连接失败");
				weightTV.setText("蓝牙连接失败");
				break;
			case BearingBlueThread.CONNECT_OBJ: // 获取蓝牙socket
				if (msg.obj != null) {
					BluetoothSocket socket = (BluetoothSocket) msg.obj;
					try {
						os = socket.getOutputStream();
						is = socket.getInputStream();
						Helper.showToast(MeasureArrivePieceBehindActivity.this,
								"蓝牙连接成功");
						weightTV.setText("蓝牙连接成功");
						new ReadThread(MeasureArrivePieceBehindActivity.this)
								.start();
					} catch (IOException e) {
						bearingBlueThread.cancelDialog();
						Helper.showToast(MeasureArrivePieceBehindActivity.this,
								"获取输入输出流异常");
						e.printStackTrace();
					}
				} else {
					weightTV.setText("蓝牙连接失败");
					Helper.showToast(MeasureArrivePieceBehindActivity.this,
							"蓝牙连接失败");
				}
				bearingBlueThread.cancelDialog();
				break;
			case BLUETOOTH_DATA_WHTA: // 获取蓝牙数据
				getWeightAndVol();
				Helper.showCanHideToast(MeasureArrivePieceBehindActivity.this,
						"收到蓝牙数据", Toast.LENGTH_SHORT);
				break;
			case CLEAR_QUEUE:
				Helper.showToast(MeasureArrivePieceBehindActivity.this, "数据清空");
				clearWeiAndVol();
				break;

			default:
				break;
			}
			return false;
		}
	});

	@Override
	protected void onResume() {
		super.onResume();
		if (bearingBlueThread == null) {
			bearingBlueThread = new BearingBlueThread(this, jHandler);
			bearingBlueThread.start();
		}
	}

	private void getWeightAndVol() {
		if (queue.peek() != null) {
			showWeiAndVol(queue.poll());
		} else {
			clearWeiAndVol();
		}
	}

	public void showWeiAndVol(JipaoqiDataEntity entity) {
		lenghtTV.setText(entity.lenght + "");
		wideTV.setText(entity.wide + "");
		highTV.setText(entity.high + "");
		weightTV.setText(entity.weight);
		volumeTV.setText(entity.volume + "");
		mData = entity;
		hasContent = true;
	}

	private void clearWeiAndVol() {
		lenghtTV.setText("");
		wideTV.setText("");
		highTV.setText("");
		weightTV.setText("");
		volumeTV.setText("");
		mData = null;
		hasContent = false;
	}

	private void selectPrevStation() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (nextStationET.getText().toString().length() == 0) {
				tableParcel.setSelectSql(SqlSelectTableManager.SQL_NETSITE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NETSITE_ONLY_LIKE);
				tableParcel.setSelectField(new String[] {
						"%" + nextStationET.getText().toString() + "%",
						"%" + nextStationET.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(SITE_CODE_NUMBER);
			tableParcel.setSelectName(SITE_CODE_NAME);
			tableParcel.setProperty(null);
			Intent intent = new Intent(this, StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, COURIER_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectPrevStation", e.getMessage());
		}
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == COURIER_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				nextStationET.setText(courierEntity.getSelectName());
				nextStationET.setSelection(nextStationET.length());
				prevStationCode = courierEntity.getSelectCode();

				if (prevStationCode.length() > 0) {
					prevStationName = courierEntity.getSelectName();
					code.requestFocus();
				}
			}
		} else if (requestCode == COURIER_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			nextStationET.setText("");
			prevStationCode = "";
			Helper.showSoundToast(this, "未检索到数据,请到业务设置中更新数据", false);
		}
	}

	@Override
	protected void handlerScanData(String scanData) {
		if (CheckScanCode(scanData)) {
			code.setText(scanData);
			processScanData();
		}
		ScanOpen();
	}

	private void processScanData() {

		if (!prevStationName.equals(nextStationET.getText().toString())) {
			Helper.showSoundToast(this, "请选择正确的上一站", false);
			return;
		}
		dealBlueData(mData);
	}

	private void doSave(JipaoqiDataEntity data) {

		//Add by wj过滤单号
		boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
		if(isFilter){
			showFilterDialog(code.getText().toString().trim());
			return;
		}
		//End by wj

		if (addPieceRecord()) {
			this.addCodeNumber();
			setSaveData(true);
			Helper.showSoundAndVibrator(this, true);
			addScanRecordInfo(code.getText().toString(), data);

		} else {
			Helper.showSoundToast(this, getString(R.string.code_repeat), false);
		}

		code.setText("");

	}

	private void dealBlueData(JipaoqiDataEntity data) {
		try {
			if (data == null) {
				Helper.showSoundToast(this, "未获取到有效数据", false);
			} else if (Float.parseFloat(data.weight) > 0f && data.volume > 0) {
				lenghtTV.setText(data.lenght + "");
				wideTV.setText(data.wide + "");
				highTV.setText(data.high + "");
				weightTV.setText(data.weight);
				volumeTV.setText(data.volume + "");
				if (TextUtils.isEmpty(code.getText().toString())) {
					Helper.showSoundToast(this, getString(R.string.code_empty),
							false);
				} else {
					doSave(data);
				}
			} else {
				Helper.showSoundToast(this, "重量体积数据必须大于0", false);
			}
		} catch (Exception e) {

			e.printStackTrace();
			Helper.showSoundToast(this, "数据解析有误", false);
		}
		clearWeiAndVol();
		ScanOpen();
	}

	private boolean addPieceRecord() {
		boolean ret;

		dataBusiness.initInsertData();
		// 扫描类型
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE
						.getOpCode());
		// 单号
		dataBusiness.setBar_code_number(code.getText().toString());
		dataBusiness.setCodeType(getExpType(code.getText().toString()));

		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 上一站
		dataBusiness.setNext_station(prevStationCode);
		// 上一站名称
		dataBusiness.setUser_defined3(nextStationET.getText().toString());
		// 插入数据
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		if (!ret && !("").equals(dataBusiness.getWeight())) {
			ret = StoDataBaseOperation.getInstance(this).replace(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
			if (ret) {
				removeItem(code.getText().toString(), 1);
			}
		}
		return ret;
	}

	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:
			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	class ReadThread extends Thread {
		private Context context;

		public ReadThread(Context context) {
			this.context = context;
		}

		@Override
		public void run() {
			super.run();
			try {
				if (os != null && is != null) {
					os.write(backCommand);
					receiverMachCode(); // 获取供包台的编号
					sendBluetoothData(); // 获得供包台返回的数据
				}
			} catch (Exception e) {
				ExceptionLog.writeLog(
						"MeasureArrivePieceBehindActivity ReadThread",
						e.getMessage());

				isFinish = true;
				closeBluetoothSocket();
				System.out.println("出异常了。。。。" + e.getMessage());
				e.printStackTrace();
			}
		}

		/**
		 * 获得供包台返回的数据，并发送给handler处理
		 * 
		 * @throws IOException
		 */
		private void sendBluetoothData() throws IOException {
			byte[] buffer = new byte[14];
			byte[] receiveBuffer = new byte[14];
			int[] saveData = null;
			int length = 0;
			int dpr = 0;
			int sum = 0;
			while (!isFinish) {
				// 报文数据起始标志
				try {
					length = is.read(buffer);
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (int i = 0; i < length; i++) {
					if ((dpr + i) < 14) {
						receiveBuffer[dpr + i] = buffer[i];
						sum++;
					} else {
						sum = 0;
						dpr = 0;
					}
				}
				System.out.println("读取的内容：" + Arrays.toString(receiveBuffer));
				if (receiveLastCommand(receiveBuffer)) {
					sum = 0;
					dpr = 0;
					buffer = new byte[14];
					receiveBuffer = new byte[14];
				} else {
					dpr = dpr + length;
					if (sum == 14) {
						sum = 0;
						dpr = 0;
						// 比较校验位
						int check = 0;
						for (int i = 1; i < 12; i++) {
							check += receiveBuffer[i];
						}
						if ((check & 0xff) == (int) (receiveBuffer[12] & 0xff)
								&& receiveBuffer[13] == 0x2A
								&& receiveBuffer[0] == 0x40) {
							saveData = new int[5];
							System.out.println("终止报文数据");
							parserData(receiveBuffer, saveData);
						} else {
							System.out.println("执行 错误数据2");
							buffer = new byte[14];
							receiveBuffer = new byte[14];
						}
					} else if ((sum > 0 && sum < 14)
							&& (receiveBuffer[0] != 0x40 || receiveBuffer[dpr - 1] == 0x2A)) {
						System.out.println("执行 错误数据1  dpr：" + dpr);
						sum = 0;
						dpr = 0;
						buffer = new byte[14];
						receiveBuffer = new byte[14];
					}
				}

			}

		}

		/**
		 * 收到终止命令
		 * 
		 * @param receiveBuffer
		 * @return
		 */
		private boolean receiveLastCommand(byte[] receiveBuffer) {
			String receiveData = Arrays.toString(receiveBuffer);
			System.out.println("receiveData: " + receiveData);
			if (receiveData.indexOf(LAST_COMMAND) > 0) {
				System.out.println("清空数据");
				queue.clear();
				jHandler.sendEmptyMessage(CLEAR_QUEUE);
				return true;
			}
			return false;
		}

		private void parserData(byte[] buf, int[] saveData) {
			// 解析长 宽 高 重量 体积
			if (saveData != null) {
				JipaoqiDataEntity entity = new JipaoqiDataEntity();
				entity.lenght = (buf[4] & 0xff);
				entity.wide = (buf[5] & 0xff);
				entity.high = (buf[6] & 0xff);
				entity.weight = dealWeight(((float) ((buf[7] & 0xff) << 8 | (buf[8] & 0xff))));
				entity.volume = ((buf[9] & 0xff) << 16 | (buf[10] & 0xff) << 8 | (buf[11] & 0xff));
				entity.jipaoqiTypeCode = machineCode;
				queue.offer(entity);
				System.out.println("添加一条重量数据：" + queue.size());
				if (queue.size() == 1 && !hasContent) { // 第一条数据且长宽高中没内容
					jHandler.sendEmptyMessage(BLUETOOTH_DATA_WHTA);
				}
			}
		}

		// 精确小数位
		private String dealWeight(float weight) {

			String retWeight = "0.0", weightStr = "0.0";
			try {
				weight = weight / 1000;
				weightStr = String.valueOf(weight);
				String str[] = weightStr.split("\\.");
				if (str.length > 1) {
					// 小数点一位
					if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_one))) {
						if (str[1].length() >= 2) {
							str[1] = str[1].substring(0, 1);
						}
					}
					// 小数点二位
					else if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_two))) {
						if (str[1].length() >= 3) {
							str[1] = str[1].substring(0, 2);
						}
					}
					// 小数点三位
					else if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_three))) {
						if (str[1].length() >= 4) {
							str[1] = str[1].substring(0, 3);
						}
					}
				} else {
					return weightStr;
				}
				retWeight = str[0] + "." + str[1];
			} catch (Exception e) {
				e.printStackTrace();

			}
			return retWeight;
		}

		/**
		 * 获取供包台的编号
		 * 
		 * @throws IOException
		 */
		private void receiverMachCode() throws IOException {
			byte[] buffer = new byte[14];
			byte[] receiveBuffer = new byte[14];
			int length = 0;
			int dpr = 0;
			int sum = 0;
			// 第一次读取后置前置协议回复
			while (!isFinish) {
				try {
					length = is.read(buffer);
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (int i = 0; i < length; i++) {
					if ((dpr + i) < 14) {
						receiveBuffer[dpr + i] = buffer[i];
						sum++;
					} else {
						sum = 0;
						dpr = 0;
					}
				}
				dpr = dpr + length;
				if (sum > 10) {
					sum = 0;
					dpr = 0;
					System.out.println("获取回复协议： "
							+ Arrays.toString(receiveBuffer));
					if (receiveBuffer[0] == 0x40) {
						if (receiveBuffer[10] == 0x2A) {
							saveMachCode(receiveBuffer);
						}
						if (receiveBuffer[13] == 0x2A) {
							parserData(receiveBuffer, new int[5]);
							// sendReceiveCommand();
						}
						System.out.println("break");
						break;
					}
				}
			}
		}

		// private void sendReceiveCommand() throws IOException {
		// if (os != null && is != null) {
		// os.write(getbytes());
		// }
		//
		// }
		//
		// private byte[] getbytes() {
		// String randomCode = RandomUtil.getRandomNumbers(12);
		// randomCode="ADD,"+randomCode;
		// byte[] bs = new byte[18];
		// bs[0] = 0x02;
		// bs[17] = 0x03;
		// int i = 1;
		// for (byte t : randomCode.getBytes()) {
		// System.out.println(t);
		// bs[i] = t;
		// i++;
		// }
		// return bs;
		// }
	}

	private void saveMachCode(byte[] buf) {
		companyMachCode = new int[5];
		companyMachCode[0] = buf[4] & 0xff;
		companyMachCode[1] = buf[5] & 0xff;
		companyMachCode[2] = buf[6] & 0xff;
		companyMachCode[3] = buf[7] & 0xff;
		companyMachCode[4] = buf[8] & 0xff;
		StringBuilder companyCode = new StringBuilder();
		for (int i = 0; i < companyMachCode.length; i++) {
			companyCode.append(companyMachCode[i]);
		}
		machineCode = companyCode.toString();
		// 保存到文件
		System.out.println("供包台的编号: " + companyCode.toString());
	}

	private void closeBluetoothSocket() {
		if (bearingBlueThread != null) {
			bearingBlueThread.cancel();
			bearingBlueThread = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isFinish = true;
		closeBluetoothSocket();
	}

	@Override
	public void onBackPressed() {
		showNotice();
	}
}
